//
//  SearchViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/6.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "SearchViewController.h"
// 用户
#import "FocusAndFansTableViewCell2.h"
#import "User.h"
#import "HomeServer.h"
// 直播
#import "LiveCollectionViewCell.h"
#import "TCPlayViewController.h"
#import "TCPlayViewController_LinkMic.h"
#import "AdsServer.h"
#import "Live.h"
// 商品
#import "MallListViewController.h"
// 订单
#import "MallCommitOrdersViewController.h"
#import "MallOrderGoodTableViewCell.h"
#import "ShopHeaderCell.h"
#import "ShopOrderFooterCell.h"
#import "MallDetailViewController.h"
#import "OrderGoods.h"
#import "PostsTextViewController.h"
#import "MallLogisticsViewController.h"

#define UserSearch @"userSearch"
#define LiveSearch @"liveSearch"
#define GoodSearch @"goodSearch"
#define OrderSearch @"orderSearch"

@interface SearchViewController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) NSString *keyWord;
@property (nonatomic, strong) NSMutableArray *historyArr;
@property (nonatomic, strong) NSString *oldKeyWord;
@property (nonatomic, strong) NSMutableArray *searchArr;

@property (nonatomic, assign) NSInteger page; // 网络请求页数

@property (nonatomic, retain) TCPlayViewController *playVC;

@property (nonatomic, strong) NSDictionary *orderStateDict;
@property (nonatomic, strong) NSDictionary *orderStateDict2;

@end

@implementation SearchViewController {
    UISearchBar     *_searchBar;
    
    // 历史记录
    UIView          *_line1;
    UILabel         *_record;
    UIButton        *_removeBtn;
    UIView          *_tagBgView;
    UIView          *_line2;
    
    // 用户
    UITableView     *_tableView;
    FocusAndFansTableViewCell2  *_userCell;
    
    // 直播
    BOOL             _hasEnterplayVC; // 直播间
    XRCarouselView  *_carouselView;
    UICollectionView *_collectionView;
    LiveCollectionViewCell *_item;
    
    // 订单
    CGSize          _size1;
    MallOrderGoodTableViewCell *_orderCell;
}

- (void)viewDidAppear:(BOOL)animated {
    _playVC = nil;
    _hasEnterplayVC = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.oldKeyWord = @"";
    self.keyWord = @"";
    // 进入请求为1
    self.page = 1;
    
    if (self.type == 1) {
        [self.historyArr addObjectsFromArray:GetUserDefaule(UserSearch)];
    }
    else if (self.type == 2) {
        [self.historyArr addObjectsFromArray:GetUserDefaule(LiveSearch)];
    }
    else if (self.type == 3) {
        [self.historyArr addObjectsFromArray:GetUserDefaule(GoodSearch)];
    }
    else
        [self.historyArr addObjectsFromArray:GetUserDefaule(OrderSearch)];
 
    [self buildUI];
    
    [self refreshData];
    
}


#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(SW(20), SW(40), SCREEN_WIDTH-SW(10), SW(10))];
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    _searchBar.delegate = self;
    // 底部的颜色
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.layer.borderWidth = 1;
    _searchBar.layer.borderColor = RGBA(236, 236, 236, 1).CGColor;
    _searchBar.layer.cornerRadius = SW(20);
    _searchBar.layer.masksToBounds = YES;
    _searchBar.searchBarStyle = UISearchBarStyleDefault;
    _searchBar.barStyle = UIBarStyleBlack;
    [self.view addSubview:_searchBar];
    [_searchBar becomeFirstResponder];
    
    _line1 = [[UIView alloc] initWithFrame:CGRectMake(0, _searchBar.y+_searchBar.height+SW(40), SCREEN_WIDTH, 1)];
    [self.view addSubview:_line1];
    _line1.backgroundColor = UISeparatedColorRGB;
    
    [self recordView];
    
    if (self.type == 1) {
        
        self.navigationItem.title = @"用户搜索";
        _searchBar.placeholder = @"请输入用户ID/昵称";
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-64-_line2.y-10) style:UITableViewStylePlain];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]init];
        [_tableView registerNib:[UINib nibWithNibName:@"FocusAndFansTableViewCell2" bundle:nil] forCellReuseIdentifier:@"cell"];
    }
    
    else if (self.type == 2) {
        
        self.navigationItem.title = @"直播搜索";
        _searchBar.placeholder = @"请输入直播间标题";
        
        // 集合视图 collectionView所有布局的父类
        // 系统提供自带的布局类
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        // 默认为纵向滑动
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        
        // 创建collectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-64-_line2.y-10) collectionViewLayout:flowLayout];
        [self.view addSubview:_collectionView];
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"LiveCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
    }
    else if (self.type == 3) {
        
        self.navigationItem.title = @"商品搜索";
        _searchBar.placeholder = @"请输入商品名称";
        
    }
    else {
        self.navigationItem.title = @"订单搜索";
        _searchBar.placeholder = @"请输入商品名/订单号";
        
        _size1 = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(12)];
        self.orderStateDict = @{@"unpaid":@[@"取消订单", @"付款"], @"paid":@[@"提醒收货"], @"delivered":@[@"查看物流", @"确认收货"], @"received":@[@"删除订单"]};
        self.orderStateDict2= @{@"unpaid":@"待付款", @"paid":@"已支付", @"delivered":@"已发货", @"received":@"交易完成"};
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-64-_line2.y-10) style:UITableViewStyleGrouped];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]init];
        
        [_tableView registerNib:[UINib nibWithNibName:@"MallOrderGoodTableViewCell" bundle:nil] forCellReuseIdentifier:@"order"];
        [_tableView registerNib:[UINib nibWithNibName:@"ShopHeaderCell" bundle:nil] forCellReuseIdentifier:@"header"];
        [_tableView registerNib:[UINib nibWithNibName:@"ShopOrderFooterCell" bundle:nil] forCellReuseIdentifier:@"footer"];
    }
    
}

- (void)recordView {
    
    _record = [[UILabel alloc] init];
    [self.view addSubview:_record];
    _record.text = @"历史记录";
    _record.textColor = [UIColor grayColor];
    _record.font = kUHSystemFontWithSize(13);
    CGSize recordSize = [LZCTools textSizeWithText:_record.text font:_record.font];
    _record.frame = CGRectMake(SW(20), _line1.y+1+SW(40), recordSize.width, recordSize.height);
    
    _removeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_removeBtn];
    [_removeBtn setTitle:@"清除记录" forState:UIControlStateNormal];
    [_removeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    _removeBtn.titleLabel.font = kUHSystemFontWithSize(13);
    _removeBtn.frame = CGRectMake(SCREEN_WIDTH-recordSize.width-SW(20), _record.y, recordSize.width, recordSize.height);
    [_removeBtn addTarget:self action:@selector(removeHistoryAction:) forControlEvents:UIControlEventTouchUpInside];
    
    _tagBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _record.y+_record.height, SCREEN_WIDTH, [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(10)].height+SW(20))];
    [self.view addSubview:_tagBgView];
    
    for (int i = 0; i < self.historyArr.count; i++) {
        CGRect frame;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_tagBgView addSubview:btn];
        [btn setBackgroundImage:[UIImage imageNamed:@"history_border"] forState:UIControlStateNormal];
        [btn setTitle:self.historyArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
        btn.titleLabel.font = kUHSystemFontWithSize(10);
        CGSize size = [LZCTools textSizeWithText:self.historyArr[i] font:kUHSystemFontWithSize(10)];
        CGFloat x;
        if (i == 0) {
            x = frame.size.width+frame.origin.x+10;
        }
        else
            x = frame.size.width+frame.origin.x+5;
        btn.frame = CGRectMake(x, SW(40)-1, size.width+10, size.height+2);
        frame = btn.frame;
        
        [btn addTarget:self action:@selector(clickHistoryAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    _line2 = [[UIView alloc] init];
    if (self.historyArr.count > 0) {
        _line2.frame = CGRectMake(0, _record.y+_record.height+SW(20)+[LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(10)].height, SCREEN_WIDTH, 10);
    }
    else {
        _line1.hidden = YES;
        _record.hidden = YES;
        _removeBtn.hidden = YES;
        _tagBgView.hidden = YES;
        _line2.frame = CGRectMake(0, _searchBar.y+_searchBar.height+SW(40), SCREEN_WIDTH, 10);
    }
    [self.view addSubview:_line2];
    _line2.backgroundColor = RGB(244, 244, 244);
}


#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    if (self.type == 1) {
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            NSLog(@"上拉加载");
            weakSelf.page++;
            [weakSelf GETUserSearch];
        }];
    }
    else if (self.type == 2) {
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            NSLog(@"上拉加载");
            weakSelf.page++;
            [weakSelf GETLivesSearch];
        }];
    }
    else if (self.type == 4) {
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            NSLog(@"上拉加载");
            weakSelf.page++;
            [weakSelf GETOrderSearch];
        }];
    }
    
}


#pragma mark ==========UISearchBar 代理响应方法==========
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
//    return YES;
//}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    NSLog(@"开始输入搜索内容");
    
    // 取消字体颜色？
    searchBar.showsCancelButton = YES;
    [searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"输入搜索完毕");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"取消搜索");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"搜索");
    
    NSString *word = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (word.length == 0) {
        [self presentViewController:[LZCTools alertMessage:@"请输入关键字"] animated:YES completion:nil];
        return;
    }
    
    
    _line1.hidden = NO;
    _record.hidden = NO;
    _removeBtn.hidden = NO;
    _tagBgView.hidden = NO;
    _record.y = _line1.y+1+SW(40);
    _removeBtn.y = _record.y;
    _tagBgView.y = _record.y+_record.height;
    _line2.y = _tagBgView.y+_tagBgView.height;
    _tableView.frame = CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-_line2.y-10);
    _collectionView.frame = CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-64-_line2.y-10);
    
    // 进入请求为1
    self.page = 1;
    
    // 保存记录
    NSString *history;
    if (word.length > 4) {
        history = [word substringToIndex:4];
    }
    else
        history = word;
    
    if (![self.historyArr containsObject:history]) {
        [self.historyArr insertObject:history atIndex:0];
        
        // 新增标签
        NSMutableArray *btnArr = [[NSMutableArray alloc] initWithArray:[_tagBgView subviews]];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        [tagBgView bringSubviewToFront:btn];
        [_tagBgView insertSubview:btn atIndex:0];
        [btn setBackgroundImage:[UIImage imageNamed:@"history_border"] forState:UIControlStateNormal];
        [btn setTitle:history forState:UIControlStateNormal];
        [btn setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
        btn.titleLabel.font = kUHSystemFontWithSize(10);
        CGSize size = [LZCTools textSizeWithText:history font:kUHSystemFontWithSize(10)];
        btn.frame = CGRectMake(10, SW(40)-1, size.width+10, size.height+2);
        CGFloat x = btn.x+btn.width+5;
        [btn addTarget:self action:@selector(clickHistoryAction:) forControlEvents:UIControlEventTouchUpInside];
        for (int i = 0; i < btnArr.count; i++) {
            UIButton *btnSub = (UIButton *)btnArr[i];
            btnSub.x = x;
            x = btnSub.x+btnSub.width+5;
        }
        
        if (btnArr.count == 5) {
            [btnArr removeObjectAtIndex:3];
            [((UIButton *)btnArr[3]) removeFromSuperview];
        }
    }
    if (self.historyArr.count==6) {
        [self.historyArr removeObjectAtIndex:5];
    }
    
//    NSString *path = [[NSString alloc] initWithFormat:@"%@", word];
//    const char *str = [path UTF8String];
//    NSString *url3 = [NSString stringWithUTF8String:str];
//    self.keyWord = [url3 stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    self.keyWord = word;
    
    if (self.type == 1) {
        SetUserDefaule(self.historyArr, UserSearch);
        
        [self GETUserSearch];
    }
    else if (self.type == 2) {
        SetUserDefaule(self.historyArr, LiveSearch);
        
        [self GETLivesSearch];
    }
    else if (self.type == 3) {
        SetUserDefaule(self.historyArr, GoodSearch);
        
        MallListViewController *listVC = [[MallListViewController alloc] init];
        listVC.titleName = self.keyWord;
        listVC.type = 2;
        [self.navigationController pushViewController:listVC animated:YES];
    }
    else if (self.type == 4) {
        SetUserDefaule(self.historyArr, OrderSearch);
        
        [self GETOrderSearch];
    }
    
    
    [searchBar resignFirstResponder];
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    
    if (self.type == 1) {
        _userCell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        User *model = self.searchArr[indexPath.row];
        
        _userCell.model = model;
        
        _userCell.optionsBtn.tag = indexPath.row;
        [_userCell.optionsBtn addTarget:self action:@selector(fansAction:) forControlEvents:UIControlEventTouchUpInside];
        
        return _userCell;
    }
    else {
        _orderCell = [tableView dequeueReusableCellWithIdentifier:@"order"];
        
        NSDictionary *dict = self.searchArr[indexPath.section];
        OrderGoods *model = ((NSArray *)dict[@"items"])[indexPath.row];
        _orderCell.model = model;
        
        if ([[self.searchArr[indexPath.section] valueForKey:@"status"] isEqualToString:@"received"]) {
            UIButton *btn;
            if (![[_orderCell.contentView.subviews lastObject] isKindOfClass:[UIButton class]]) {
                
                btn = [UIButton buttonWithType:UIButtonTypeCustom];
                [_orderCell.contentView addSubview:btn];
                CGFloat btnW = _size1.width*2 + 10;
                CGFloat x = SCREEN_WIDTH - (10+btnW);
                btn.frame = CGRectMake(x, _orderCell.contentView.height-10-(_size1.height+5), btnW, _size1.height+5);
                btn.titleLabel.font = kUHSystemFontWithSize(12);
                [btn setTitle:@"评价" forState:UIControlStateNormal];
                btn.layer.borderWidth = 1;
                btn.layer.cornerRadius = 10;
                btn.layer.masksToBounds = YES;
                
                btn.layer.borderColor = kRedColor.CGColor;
                [btn setTitleColor:kRedColor forState:UIControlStateNormal];
                
                [btn addActionWithblock:^{
                    PostsTextViewController *postVC = [[PostsTextViewController alloc] init];
                    postVC.type = @"1";
                    postVC.goodId = [model valueForKey:@"goods_id"];
                    [self presentViewController:postVC animated:YES completion:nil];
                }];
            }
            
        }
        
        return _orderCell;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.type == 4) {
        return self.searchArr.count;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.type == 1) {
        
        
        return self.searchArr.count;
        
        
    }
    else {
        NSDictionary *dict = self.searchArr[section];
        return ((NSArray *)dict[@"items"]).count;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == 1) {
        return SW(7)+20;
    }
    else
        return 2*SW(9)+10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", (long)indexPath.row);
    
    if (self.type == 4) {
        NSDictionary *dict = self.searchArr[indexPath.section];
        OrderGoods *model = ((NSArray *)dict[@"items"])[indexPath.row];
        
        MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
        detailVC.goodId = [[model valueForKey:@"goods_id"] integerValue];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}


//   tableView代理方法 设置分区高度（可以根据不同分区设置不同高度等实现自定义）
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.type == 1) {
        return 0;
    }
    else
        return _size1.height+40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.type == 1) {
        return 0;
    }
    else
        return 89;
}

//  自定义分区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.type != 4) {
        return nil;
    }

    
    ShopHeaderCell *hf = [tableView dequeueReusableCellWithIdentifier:@"header"];
    NSString *imgStr = [[self.searchArr[section] valueForKey:@"shop"] valueForKey:@"photo"];
    [hf.pic sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:IMAGE(@"placeHolder")];
    hf.state.text = self.orderStateDict2[[self.searchArr[section] valueForKey:@"status"]];
    hf.name.text = [[self.searchArr[section] valueForKey:@"shop"] valueForKey:@"shop_name"];
    
    return hf;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (self.type != 4) {
        return nil;
    }
    
    ShopOrderFooterCell *ff = [tableView dequeueReusableCellWithIdentifier:@"footer"];
    
    
    int num = 0;
    float price = 0.0;
    float express_fee = 0.0;
    
    NSDictionary *orderDict = self.searchArr[section];
    
    num = (int)((NSArray *)orderDict[@"items"]).count;
    price = [orderDict[@"total_price"] floatValue]/100;
    express_fee = [orderDict[@"express_fee"] floatValue]/100;
    
    if (express_fee == 0.0) {
        ff.price.text = [NSString stringWithFormat:@"合计:%.2lf(免运费)", price];
    }
    else
        ff.price.text = [NSString stringWithFormat:@"合计:%.2lf(运费:%.2lf)", price, express_fee];
    
    ff.num.text = [NSString stringWithFormat:@"共%d件商品", num];
    
    NSArray *arr = self.orderStateDict[orderDict[@"status"]];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [ff.contentView addSubview:btn];
        CGFloat btnW = _size1.width*2 + 10;
        CGFloat x = SCREEN_WIDTH - (10+btnW)*(arr.count-i);
        btn.frame = CGRectMake(x, 0, btnW, _size1.height+5);
        btn.centerY = ff.contentView .height-25;
        btn.titleLabel.font = kUHSystemFontWithSize(12);
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        btn.layer.borderWidth = 1;
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
        
        if (i==0) {
            btn.layer.borderColor = kBlackColor.CGColor;
            [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
        }
        else {
            btn.layer.borderColor = kRedColor.CGColor;
            [btn setTitleColor:kRedColor forState:UIControlStateNormal];
        }
        
        btn.tag = (section+1)*1000+i; // 确定数据
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return ff;
    
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    _item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    
    _item.model = self.searchArr[indexPath.row];
    
    return _item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.searchArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    NSLog(@"%f", _item.cover.height);
    return CGSizeMake(SW(2), SW(2));
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"点击collectionView.item = %ld", indexPath.row);
    
    Live *model = self.searchArr[indexPath.row];
    
    [self PUTLive:[model.anchor valueForKey:@"user_id"]];
    
}

#pragma mark ==========响应方法==========
- (void)clickHistoryAction:(UIButton *)sender {
    [_searchBar becomeFirstResponder];
    _searchBar.text = sender.titleLabel.text;
    
//    NSString *path = [[NSString alloc] initWithFormat:@"%@", _searchBar.text];
//    const char *str = [path UTF8String];
//    NSString *url3 = [NSString stringWithUTF8String:str];
//    self.keyWord = [url3 stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    self.keyWord = _searchBar.text;
    
//    [self GETUserSearch];
    if (self.type == 1) {
        [self GETUserSearch];
    }
    else if (self.type == 2) {
        [self GETLivesSearch];
    }
    else if (self.type == 3) {
        MallListViewController *listVC = [[MallListViewController alloc] init];
        listVC.titleName = self.keyWord;
        listVC.type = 2;
        [self.navigationController pushViewController:listVC animated:YES];
    }
    else if (self.type == 4) {
        [self GETOrderSearch];
    }
    [_searchBar resignFirstResponder];
    
}

- (void)removeHistoryAction:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否清除所有历史记录？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"不" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"清除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.historyArr removeAllObjects];
        [[NSUserDefaults standardUserDefaults] setObject:self.historyArr forKey:@""];
        
        _line1.hidden = YES;
        _record.hidden = YES;
        sender.hidden = YES;
        _tagBgView.hidden = YES;
        [_tagBgView removeAllSubViews];
        _line2.frame = CGRectMake(0, _searchBar.y+_searchBar.height+SW(40), SCREEN_WIDTH, 10);
        _tableView.frame = CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-64-_line2.y-10);
        _collectionView.frame = CGRectMake(0, _line2.y+10, SCREEN_WIDTH, SCREEN_HEIGHT-64-_line2.y-10);
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}


// 搜索用户
- (void)GETUserSearch {
    
    if ([self.keyWord isEqualToString:@""]) {
        [_tableView.mj_footer endRefreshing];
        return;
    }
    
    NSDictionary *param = @{@"keyword":self.keyWord,
                            @"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    [[NetworkTool sharedTool] requestWithName:@"搜索用户信息" URLString:APIUserInfos parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        if (arr.count == 0 && self.searchArr.count == 0) {
            [_tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self presentViewController:[LZCTools alertMessage:@"没有这个用户"] animated:YES completion:nil];
            return ;
        }
        
        if (![self.oldKeyWord isEqualToString:_searchBar.text]) {
            self.page = 1;
            [self.searchArr removeAllObjects];
        }
        self.oldKeyWord = _searchBar.text;
        if (self.page == 1) {
            [self.searchArr removeAllObjects];
        }
        
        for (NSDictionary *dict in arr) {
            User *model = [[User alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.searchArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView.mj_footer endRefreshing];
            
            NSLog(@"reload");
            
            [_tableView reloadData];
        });
        
    }];
}
// 搜索直播

- (void)GETLivesSearch {
    
    if ([self.keyWord isEqualToString:@""]) {
        [_collectionView.mj_footer endRefreshing];
        return;
    }
    
    //GET /lives 获取直播列表 ? page 页码 tag_id 分类ID per_page 每页显示数 keyword 关键词 支持直播标题
    
    NSDictionary *param = @{@"per_page":@"10", @"page":[NSString stringWithFormat:@"%ld", self.page], @"keyword":self.keyWord};
    
    [[NetworkTool sharedTool] requestWithName:@"获取直播" URLString:APILives parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        if (arr.count == 0 && self.searchArr.count == 0) {
            [_collectionView.mj_footer endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self presentViewController:[LZCTools alertMessage:@"没有这个直播"] animated:YES completion:nil];
            return ;
        }
        
        if (![self.oldKeyWord isEqualToString:_searchBar.text]) {
            self.page = 1;
            [self.searchArr removeAllObjects];
        }
        self.oldKeyWord = _searchBar.text;
        if (self.page == 1) {
            [self.searchArr removeAllObjects];
        }
        
        for (NSDictionary *dict in arr) {
            Live *model = [[Live alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.searchArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_collectionView.mj_footer endRefreshing];
            [_collectionView reloadData];
        });
        
    }];
}

// 搜索订单
- (void)GETOrderSearch {
    
    if ([self.keyWord isEqualToString:@""]) {
        [_tableView.mj_footer endRefreshing];
        return;
    }
    
    NSDictionary *param = @{@"keyword":self.keyWord,
                            @"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    [[NetworkTool sharedTool] requestWithName:@"搜索订单" URLString:APIMallsOrders parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        if (arr.count == 0 && self.searchArr.count == 0) {
            [_tableView.mj_footer endRefreshing];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self presentViewController:[LZCTools alertMessage:@"没有相关订单"] animated:YES completion:nil];
            return ;
        }
        
        if (![self.oldKeyWord isEqualToString:_searchBar.text]) {
            self.page = 1;
            [self.searchArr removeAllObjects];
        }
        self.oldKeyWord = _searchBar.text;
        if (self.page == 1) {
            [self.searchArr removeAllObjects];
        }
        
//        for (NSDictionary *dict in arr) {
//            User *model = [[User alloc] init];
//            [model setValuesForKeysWithDictionary:dict];
//            [self.searchArr addObject:model];
//        }
        self.searchArr = [self.searchArr arrayByAddingObjectsFromArray:arr].mutableCopy;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
        
    }];
    
}

/**
 添加关注 or 取消关注
 */
- (void)fansAction:(UIButton *)sender {
    
    User *model = self.searchArr[sender.tag];
    NSString *toId = [model valueForKey:@"user_id"];
    
    [HomeServer focus:sender toId:toId];
}



/**
 进入直播间
 */
- (void)PUTLive:(NSString *)userId {
    
    
    // PUT /users/{uid}/lives 进入直播间 只有主播进入都会有推流地址 uid * 主播ID
    NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", userId];
    
    [[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
        
        if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:userId]) {
            NSLog(@"这个直播是自己的直播直播，走创建流程");
        }
        
        Live *model = [[Live alloc] init];
        [model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
        
        
        TCLiveInfo *info = [[TCLiveInfo alloc] init];
        info.userinfo = [[TCLiveUserInfo alloc] init];
        
        info.userid = [model.anchor valueForKey:@"user_id"];
        info.groupid = model.chatroom_id;
        info.likecount = [model.like_num intValue];
        info.title = model.title;
        info.playurl = model.pull_url[0]; // rtmp 默认第一个
        info.timestamp = [model.start_time intValue];
        info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
        info.userinfo.headpic = [model.anchor valueForKey:@"face"];
        info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
        info.isLike = [model.anchor valueForKey:@"is_like"];
        info.money = [model.anchor valueForKey:@"money"];
        info.viewercount = (int)model.viewer_num;
        info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
        
        //        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
        
        info.isVip = @"1";
        info.myuserid = [model.anchor valueForKey:@"user_id"];
        
        
        // 保存直播信息，后面用到
        NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
        SetUserDefaule(live, CURRLIVE);
        
        NSDictionary *userinfo = GetUserDefaule(USERINFO);
        
        NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
                                   @"uid":[userinfo valueForKey:@"user_id"],
                                   @"nickname":[userinfo valueForKey:@"nickname"],
                                   @"headpic":[userinfo valueForKey:@"face"],
                                   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
        
        
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
        NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        info.senderInfo = infoStr;
        
        // MARK: 打开播放界面
        if (_playVC == nil) {
            _playVC = [[TCPlayViewController_LinkMic alloc] initWithPlayInfo:info videoIsReady:^{
                if (!_hasEnterplayVC) {
                    [self.navigationController pushViewController:_playVC animated:YES];
                    _hasEnterplayVC = YES;
                }
            }];
        }
        
        [self performSelector:@selector(enterPlayVC:) withObject:_playVC afterDelay:0.5];
        
    }];
}

-(void)enterPlayVC:(NSObject *)obj{
    if (!_hasEnterplayVC) {
        [self.navigationController pushViewController:_playVC animated:YES];
        _hasEnterplayVC = YES;
    }
}

// 订单操作

- (void)btnClick:(UIButton *)btn {
    
    NSInteger section = btn.tag/1000 - 1;
    NSDictionary *orderDict = self.searchArr[section];
    NSString *orderId = orderDict[@"order_id"];
    
    if ([orderDict[@"status"] isEqualToString:@"unpaid"]) {
        if (btn.tag%2 == 0) {
            NSString *url = [NSString stringWithFormat:@"%@/%@", APIMallsOrders, orderId];
            
            [[NetworkTool sharedTool] requestWithName:@"取消订单" URLString:url parameters:nil method:@"DELETE" callBack:^(id responseObject) {
                
                [self.searchArr removeObjectAtIndex:section];
                [_tableView reloadData];
            }];
        }
        else {
            MallCommitOrdersViewController *commitVC = [[MallCommitOrdersViewController alloc] init];
            commitVC.orderData = @[self.searchArr[section]]; // 介于购物车缘故，传递数组
            [self.navigationController pushViewController:commitVC animated:YES];
        }
        
    }
    else if ([orderDict[@"status"] isEqualToString:@"paid"]) {
        [LZCTools HUDMessage:@"提醒成功" delay:2.0];
    }
    else if ([orderDict[@"status"] isEqualToString:@"delivered"]) {
        if (btn.tag%2 == 0) {
            MallLogisticsViewController *logisticsVC = [[MallLogisticsViewController alloc] init];
            logisticsVC.goodId = orderId;
            [self.navigationController pushViewController:logisticsVC animated:YES];
        }
        else {
            NSString *url = [NSString stringWithFormat:@"%@/%@/receive-status", APIMallsOrders, orderId];
            
            [[NetworkTool sharedTool] requestWithName:@"确认收货" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
                [self.searchArr removeObjectAtIndex:section];
                [_tableView reloadData];
            }];
        }
    }
    else {
        NSString *url = [NSString stringWithFormat:@"%@/%@/hidden", APIMallsOrders, orderId];
        [[NetworkTool sharedTool] requestWithName:@"删除订单" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
            [self.searchArr removeObjectAtIndex:section];
            [_tableView reloadData];
        }];
        
    }
    
}

// 懒加载

- (NSMutableArray *)searchArr {
    if (_searchArr == nil) {
        _searchArr = [[NSMutableArray alloc] init];
    }
    return _searchArr;
}
- (NSMutableArray *)historyArr {
    if (_historyArr == nil) {
        _historyArr = [[NSMutableArray alloc] init];
    }
    return _historyArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
